package com.tjtt.tdm.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.exception.DaoException;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.system.bean.Organization;
import com.tjtt.tdm.system.bean.UserRole;
import com.tjtt.tdm.system.bean.Users;
import com.tjtt.tdm.system.dao.UserDao;
import com.tjtt.tdm.system.dao.UserRoleDao;
import com.tjtt.tdm.system.service.UserService;

public class UserServiceImpl implements UserService {
	private static final Log log = LogFactory.getLog(UserServiceImpl.class);
	private UserDao userDao;
	private UserRoleDao userRoleDao;

	public UserRoleDao getUserRoleDao() {
		return userRoleDao;
	}

	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public Users checkUser(String loginName,String psw) throws ServiceException{
		Users user = null;
		List<Users> userList;
		try {
			userList = userDao.findByProperties(new String[] {
					"loginname", "psw" ,"delFlag"}, new String[] { loginName, psw ,"1"});
			if (userList != null && userList.size() == 1) {
				user = userList.get(0);
			}
			return user;
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	
	public List<Users> findUsers(HashMap<String, Object> paramMap,
			long totalCount, long start, long limit, String sort, String dir)
			throws ServiceException {
		if (start > totalCount) {
			start = totalCount - (totalCount % limit);
		}
		try {
			return userDao.findByProperties(start, limit, sort, dir, paramMap);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}

	public Long getTotalCount(HashMap<String, Object> paramMap)
			throws ServiceException {
		try {
			return userDao.getTotalCount(paramMap);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}

	public Users getUsers(Long userId) throws ServiceException {
		try {
			return userDao.get(userId);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	
	
	public void updateUsers(Users user,String roleIds) throws ServiceException {
		Users updateUser = getUsers(user.getUserid());
		updateUser.setActive(user.getActive());
		updateUser.setAddress(user.getAddress());
		updateUser.setEmail(user.getEmail());
		updateUser.setFixedPhone(user.getFixedPhone());
		updateUser.setCompanyTel(user.getCompanyTel());
		updateUser.setMobile(user.getMobile());
		updateUser.setUserdesc(user.getUserdesc());
		updateUser.setSex(user.getSex());
		updateUser.setUsername(user.getUsername());
		updateUser.setOrganization(user.getOrganization());
		//updateUser.setPosName(user.getPosName());
		updateUser.setJobName(user.getJobName());
		updateUser.setSecurityClass(user.getSecurityClass());
		updateUser.setImgPath(user.getImgPath());
		updateUser.setSignPath(user.getSignPath());
		updateUser.setImgAddress(user.getImgAddress());
		updateUser.setSignAddress(user.getSignAddress());
		if(null != user.getPwdEditTime()){
			updateUser.setPwdEditTime(user.getPwdEditTime());
		}
		try {
			//更新用户基本信息
			userDao.update(updateUser);
			//  删除原有的角色关联
			userRoleDao.removeByParams("userid", new Long []{updateUser.getUserid()});
			// 新加角色组
			if(StringUtils.isNotEmpty(roleIds)){
				List<UserRole> listUserRole=new ArrayList<UserRole>();
				String[] ids= roleIds.split(",");
				for(String idString :ids){
					UserRole urRole = new UserRole();
					urRole.setRoleid(Long.parseLong(idString));
					urRole.setUserid(user.getUserid());
					listUserRole.add(urRole);
				}
				userRoleDao.saveOrUpdateAll(listUserRole);
			} 
			
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
		
	}
	
	public void saveUsers(Users user,String roleIds) throws ServiceException{
		try {
			userDao.saveOrUpdate(user);//保存用户信息
			if(StringUtils.isNotEmpty(roleIds)){
				List<UserRole> listUserRole=new ArrayList<UserRole>();
				String[] ids= roleIds.split(",");
				for(String idString :ids){
					UserRole urRole = new UserRole();
					urRole.setRoleid(Long.parseLong(idString));
					urRole.setUserid(user.getUserid());
					listUserRole.add(urRole);
				}
				userRoleDao.saveOrUpdateAll(listUserRole);
			} 
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}

	

	public Long getTotalCountByRoleId(HashMap<String, Object> paramMap)
			throws ServiceException {
		try {
			return userRoleDao.getTotalCount(paramMap);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	
	
	/**根据组织结构的Id查询用户*/
	public List<Users> findUsersByOrgId(int start,int limit,Long orgId) throws ServiceException {
		try {
			/*String[] names;
			Object[] objs;
			if(orgId!=1){
				names=new String[2];
				names[0]="delFlag";
				names[1]="organization.orgId";
				objs=new Object[2];
				objs[0]=1+"";
				objs[1]=orgId;
			}else{
				names=new String[1];
				names[0]="delFlag";
				objs=new Object[1];
				objs[0]=1+"";
			}
			List<Users> list=userDao.findByProperties(names, objs);
			*/
			List<Users> list = userDao.findUserByOrgId(start,limit,orgId);
			return list;
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}

	/**根据角色的Id查询用户*/
	public List<Users> findUsersByRoleId(Long roleId) throws ServiceException {
		try {			
			//return userDao.findByProperty("role.roleid", roleId);
			List<Users> userList=new ArrayList<Users>();
			String sql = "select * from SYS_USERS t where t.userid in (select SYS_USER_ROLE.userid from SYS_USER_ROLE  where SYS_USER_ROLE.ROLEID="+roleId+") and t.del_flag='1'";
		    List users=userDao.findBySQL(sql);
			for (int i = 0; i < users.size(); i++) {
				Map map=(Map) users.get(i);
				Long userId=Long.parseLong(map.get("USERID").toString());
				Users user=userDao.get(userId);
				userList.add(user);
			}
			return userList;
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	/**根据角色的Id分页查询用户*/
	public List<Users> searchUsersByRoleId(Long roleId,long start,
			long limit) throws ServiceException {
		try {			
			List<Users> userList=new ArrayList<Users>();
			long rownum = start + limit;
			String sql ="select * from (select rownum as rown,u.* from (select * from SYS_USERS t where t.userid in (select SYS_USER_ROLE.userid from SYS_USER_ROLE  where SYS_USER_ROLE.ROLEID="+roleId+") and t.del_flag='1')u where rownum<= "+rownum+")where rown> "+start+"";
			List users=userDao.findBySQL(sql);
			for (int i = 0; i < users.size(); i++) {
				Map map=(Map) users.get(i);
				Long userId=Long.parseLong(map.get("USERID").toString());
				Users user=userDao.get(userId);
				userList.add(user);
			}
			return userList;
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	public List<Users> findAllUsersByRoleId(HashMap<String, Object> paramMap,
			long totalCount, long start, long limit, String sort, String dir)
			throws ServiceException {
		if (start > totalCount) {
			start = totalCount - (totalCount % limit);
		}
		try {
			return userDao.getAll();
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}


	public List findFirstMenu(String role) throws ServiceException {
		String hql = "SELECT DISTINCT M.MENUID,M.MENUNAME,M.PARENTID,M.URL,M.SEQUENCE FROM SYS_ROLEMENU R LEFT JOIN SYS_MENU M ON M.MENUID=R.MENUID WHERE R.ROLEID IN("+role+") ORDER BY M.SEQUENCE";
		try {
			List menuList = userDao.findBySQL(hql);
			return menuList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	public void updatePswEditTime(Long userId) throws ServiceException {
		String sql = "UPDATE SYS_USERS SET PWD_EDIT_TIME = SYSDATE WHERE USERID = "+userId;
		try {
			this.userDao.executeSQL(sql);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
 
	public List findOftenMenu(String userId) throws ServiceException {
		String hql = "SELECT R.ID,M.MENUID,M.MENUNAME,M.PARENTID,M.URL FROM SYS_OFTEN_MENU R LEFT JOIN SYS_MENU M ON M.MENUID=R.MENU_ID WHERE r.USER_ID="+userId+"";
		try {
			List menuList = userDao.findBySQL(hql);
			return menuList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public void editUserInfo(Users user) throws ServiceException {
		try {
			//更新用户基本信息
			userDao.update(user);		
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
    
	public void updateUserInfo(Users user) throws ServiceException {
		Users updateUser = getUsers(user.getUserid());
		updateUser.setEmail(user.getEmail());
		updateUser.setCompanyTel(user.getCompanyTel());
		updateUser.setMobile(user.getMobile());
		updateUser.setUsername(user.getUsername());
		updateUser.setImgPath(user.getImgPath());
		updateUser.setSignPath(user.getSignPath());
		updateUser.setImgAddress(user.getImgAddress());
		updateUser.setSignAddress(user.getSignAddress());
		updateUser.setCertificateAddress(user.getCertificateAddress());
		updateUser.setCertificatePath(user.getCertificatePath());
		updateUser.setStampPath(user.getStampPath());
		updateUser.setStampAddress(user.getStampAddress());
		updateUser.setSex(user.getSex());
		//updateUser.setPosName(user.getPosName());
		if(null != user.getPsw() && user.getPsw().length()!=0){
			updateUser.setPsw(user.getPsw());
		}
		if(null != user.getPwdEditTime()){
			updateUser.setPwdEditTime(user.getPwdEditTime());
		}
		try {
			//更新用户基本信息
			userDao.update(updateUser);		
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}

	public Users findUsersById(long userid) {
		return this.userDao.getUsersById(userid);
	}

	public List<Users> getListByHql(Integer start, Integer limit, String sort,
			String dir, String wheresql) throws DaoException {
		
		return this.userDao.getList(start, limit, sort, dir, wheresql);
	}
	
	public long getTotalCountByWhereHql(String wheresql) throws DaoException {		
		return this.userDao.getTotalCount(wheresql);
	}

	//根据登录名查询用户
	public Users findUsersByName(String loginname) {
		return this.userDao.findUsersByName(loginname);
	}

	//根据组织id查询用户
	public String findUserDelflagByOrgId(String ids) {
		return this.userDao.findUserDelflagByOrgId(ids);
	}

	//根据组织id查询用户
	public PageResult queryUserList(Map filterMap) throws ServiceException {
		return this.userDao.queryUserList(filterMap);
	}

	
	public PageResult queryUser(Map filterMap) {
		return this.userDao.queryUser(filterMap);
	}

	
	public Users findUsersByloginName(String loginname) {
		return userDao.findUsersByloginName(loginname);
	}

	
	public Organization findOrganationByorgId(Long orgId) {
		return this.userDao.getOrganationByorgId(orgId);
	}

	
	public PageResult queryUserList2(Map<String, String> filterMap) {
		return this.userDao.queryUserList2(filterMap);
	}

	public Users findUsersByUserName(String username)
	{
		return this.userDao.findUsersByUserName(username);
	}
	public Long getCroleByRoleId(HashMap<String, Object> paramMap)
		throws ServiceException {
		try {
			return userRoleDao.getCroleByRoleId(paramMap);
		} catch (DaoException e) {
			log.error(e.getMessage());
			throw new ServiceException(e.getMessage(), e);
		}
	}
	public PageResult queryChooseData(Map<String, String> filterMap) 
	{
		return userDao.queryChooseData(filterMap);
	}
	public List getDatabySql(String sql){
		return userDao.getDatabySql(sql);
	}
}